import api from '../../utils/request';

Page({
  data: {
    schedules: [],
    loading: false,
    currentDate: '',
    direction: 'A_to_B',
    directions: [
      { value: 'A_to_B', label: 'A → B' },
      { value: 'B_to_A', label: 'B → A' }
    ],
    page: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.setData({
      currentDate: this.formatDate(new Date())
    });
    this.loadSchedules();
  },

  // 加载班车列表
  async loadSchedules(refresh = false) {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      const params = {
        date: this.data.currentDate,
        route_direction: this.data.direction,
        page: refresh ? 1 : this.data.page,
        page_size: this.data.pageSize
      };
      
      const res = await api.schedule.getList(params);
      
      this.setData({
        schedules: refresh ? res.data.items : [...this.data.schedules, ...res.data.items],
        page: refresh ? 2 : this.data.page + 1,
        hasMore: res.data.items.length === this.data.pageSize,
        loading: false
      });
    } catch (error) {
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 切换方向
  onDirectionChange(e) {
    this.setData({
      direction: e.detail.value,
      schedules: [],
      page: 1,
      hasMore: true
    });
    this.loadSchedules(true);
  },

  // 选择日期
  onDateChange(e) {
    this.setData({
      currentDate: e.detail.value,
      schedules: [],
      page: 1,
      hasMore: true
    });
    this.loadSchedules(true);
  },

  // 查看详情
  onScheduleClick(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/schedule/detail?id=${id}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadSchedules(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSchedules();
    }
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
}); 